from rest_framework import serializers
from apps.users.models import User
# serializer 序列化器
# 作用：将模型对象转换为字典，或者将字典转换为模型对象
# serializer.ModelSerializer 模型序列化器
# 作用：快速实现模型对象与字典的转换
# 步骤：
# 1. 定义一个序列化器类，继承自serializers.ModelSerializer
# 2. 在Meta类中指定模型类和字段


class UserModelSerializer(serializers.ModelSerializer):
    # password = serializers.CharField(write_only=True, max_length=15, min_length=4)
    """用户序列化器"""
    class Meta: # 指定模型类和字段
        model = User
        fields = ['id', 'username', 'mobile', 'password','email']
        extra_kwargs = {
            'password':{
                'write_only':True,
                'max_length':15,
                'min_length':4
                }
        }
    def create(self, validated_data):
        return User.objects.create_user(**validated_data)
        #或者
        # user = User.objects.create(**validated_data)
        # user.set_password(validated_data['password'])
        # user.save()
        # return user
